/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sismol.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import sismol.cartography.Ponto;
import sismol.cartography.TrechoAtual;
import sismol.data.GerenciadorBusca;
import sismol.data.GerenciadorFactory;

/**
 *
 * @author Koji
 */
public class ViewAction  extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("application/json");

        // Faz a busca da situação atual da linha para visualização.
        Long linhaId = Long.valueOf(request.getParameter("linhaId"));

        // Retorna um JSON.
        PrintWriter writer = response.getWriter();

        try {
            writer.print(this.buscaLinha(linhaId));
        } catch(JSONException e) {
            //
        }
    }

    private JSONObject buscaLinha(Long linhaId) throws JSONException {
        GerenciadorBusca busca = GerenciadorFactory.getGerenciadorBusca();

        // Busca os dados da linha para desenhar o mapa.
        List<Ponto> pontos = busca.listarPontosPorLinha(linhaId);

        JSONObject linha = new JSONObject();
        linha.put("origin", this.preenchePonto(pontos.remove(0)));
        linha.put("destination", this.preenchePonto(pontos.remove(pontos.size() - 1)));

        JSONArray waypoints = new JSONArray();
        for (Ponto ponto : pontos) {
            waypoints.put(this.preenchePonto(ponto));
        }
        linha.put("waypoints", waypoints);
        
        // Busca a posição dos ônibus para exibí-los no mapa.
        List<TrechoAtual> posicoes = (List<TrechoAtual>) busca.buscaPosicaoDosOnibusDaLinha(linhaId);
        JSONArray listOnibus = new JSONArray();
        for (TrechoAtual trechoAtual : posicoes) {
            JSONObject onibus = new JSONObject();
            onibus.put("lat", trechoAtual.getLatitude());
            onibus.put("lng", trechoAtual.getLongitude());
            onibus.put("velocidade", trechoAtual.getVelocidade());

            listOnibus.put(onibus);
        }

        // Monta objeto de retorno
        JSONObject object = new JSONObject();
        object.put("linha", linha);
        object.put("onibus", listOnibus);
        return object;
    }

    private JSONObject preenchePonto(Ponto ponto) throws JSONException {
        JSONObject json = new JSONObject();

        json.put("id", ponto.getId());
        json.put("lat", ponto.getLatitude());
        json.put("lng", ponto.getLongitude());
        json.put("parada", ponto.getParada());
        json.put("nome", ponto.getNome());

        return json;
    }


    // <editor-fold defaultstate="collapsed" desc="MÃ©todos HttpServlet. Clique no sinal de + Ã  esquerda para editar o cÃ³digo.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
